package com.km.wskj.itmonitor.pager.monitor.server;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.fingdo.statelayout.StateLayout;
import com.github.lzyzsd.circleprogress.DonutProgress;
import com.github.mikephil.charting.charts.LineChart;
import com.km.wskj.itmonitor.R;
import com.km.wskj.itmonitor.http.ZxlGenericsCallback;
import com.km.wskj.itmonitor.model.Cpu;
import com.km.wskj.itmonitor.model.FuncItem;
import com.km.wskj.itmonitor.model.ServerTypeDetail;
import com.km.wskj.itmonitor.pager.base.LActivity;
import com.km.wskj.itmonitor.pager.monitor.AlarmListNoSpinnerActivity;
import com.km.wskj.itmonitor.pager.monitor.database.DBListActivity;
import com.km.wskj.itmonitor.utils.DynamicChartUtils;
import com.zxl.zxlapplibrary.util.LogUtils;
import com.zxl.zxlapplibrary.view.MyGridView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;


/**
 * @author by Xianling.Zhou on 2017/2/9.
 */
//服务器详情页面
public class ServerDetailActivity extends LActivity {
    //ui
    @BindView(R.id.tv_std_disk_space)
    TextView mDiskSpace;
    @BindView(R.id.tv_std_memory_space)
    TextView mMemorySpace;
    @BindView(R.id.tv_std_percent)
    TextView mPercent;
    @BindView(R.id.tool_bar_title)
    TextView mTitle;
    @BindView(R.id.tool_bar_back)
    ImageView mBack;
    @BindView(R.id.tool_bar_right_text)
    TextView mRightText;
    @BindView(R.id.std_lineChart)
    LineChart mChart;
    @BindView(R.id.sd_container_gridview)
    LinearLayout mContainer_gridview;
    @BindView(R.id.donutProgress)
    DonutProgress donutProgress;
    @BindView(R.id.state_layout)
    StateLayout stateLayout;


    //data
    List<FuncItem> funcItems = new ArrayList<>();
    MyGridView gridView;
    String id;
    String ip;
    ServerTypeDetail std;
    Cpu sc;

    private static Handler handler = new Handler();

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // 在此处添加执行的代码
            initData();
            handler.postDelayed(this, 2000);// 5000ms后执行this，即runable
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_server_detail);
        ButterKnife.bind(this);

        if (getIntent().hasExtra("id"))
            id = getIntent().getStringExtra("id");
        if (getIntent().hasExtra("ip"))
            ip = getIntent().getStringExtra("ip");

        mTitle.setText(ip);
        mBack.setVisibility(View.VISIBLE);
        mRightText.setVisibility(View.VISIBLE);
        mRightText.setText("报告");


        initData();
        // 打开定时器，5000ms后执行runnable操作
        handler.postDelayed(runnable, 2000);

        //初始化chart
        DynamicChartUtils.initChart(mChart, Color.parseColor("#ffffff"));

        initFuncItems();
        mContainer_gridview.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                mContainer_gridview.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                createGridView();
            }
        });
    }

    /**
     * 初始化数据
     */
    private void initData() {
        //服务器详情
        pdc.serverDetail(HTTP_TASK_TAG, id, new ZxlGenericsCallback<ServerTypeDetail>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e("error", e);
            }

            @Override
            public void onResponse(ServerTypeDetail serverTypeDetail, int i) {
                std = serverTypeDetail;
                initServerView();
            }
        });

        //服务器cpu详情
        pdc.cpu(HTTP_TASK_TAG, ip, new ZxlGenericsCallback<Cpu>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e("error", e);
            }

            @Override
            public void onResponse(Cpu cpu, int i) {
                sc = cpu;
                initCpuView();
            }
        });
    }

    private void initCpuView() {
        if (sc.total != null) {
            mPercent.setText(sc.total + "%");
            //动态添加折线图数据
            DynamicChartUtils.addEntry(mChart, Float.parseFloat(sc.total));
        }
    }

    private void initServerView() {
        if (std != null) {
            String total = std.diskTotal;
            float g = std.memory / Float.parseFloat(total.substring(0, total.lastIndexOf("G")));
            float b = (float) (Math.round(g * 1000)) / 1000;//(这里的100就是2位小数点,如果要其它位,如4位,这里两个100改成10000)
            donutProgress.setProgress(b * 100);
            donutProgress.setText(b * 100 + "%");
            donutProgress.setInnerBottomText("已占用内存");
            mDiskSpace.setText(std.diskTotal);
            mMemorySpace.setText(std.memory + "GB");
        }
    }

    @Override
    protected void onDestroy() {
        handler.removeCallbacks(runnable);
        super.onDestroy();
    }

    private void initFuncItems() {
        String s[] = getResources().getStringArray(R.array.server_func_title_array);
        int r[] = {R.mipmap.alarm_blue
                , R.mipmap.memory_blue
                , R.mipmap.cpu_blue
                , R.mipmap.ccxx_blue
                , R.mipmap.yjxx_blue
                , R.mipmap.lsxn_blue
                , R.mipmap.config_blue
                , R.mipmap.zt_blue
                , R.mipmap.fw_blue
                , R.mipmap.jxsm_blue
                , R.mipmap.aqld_blue
                , R.mipmap.qt_blue
                , R.mipmap.db_blue
                , R.mipmap.zjj_blue
                , R.mipmap.gl_blue};


        funcItems.clear();
        for (int i = 0; i < s.length && i < r.length; i++) {
            FuncItem fi = new FuncItem();
            fi.name = s[i];
            fi.resId = r[i];
            funcItems.add(fi);
        }
    }

    private void createGridView() {
        gridView = new MyGridView(context, new MyGridView.MyGridViewAdapter() {
            @Override
            public int rowspacing(MyGridView myGridView) {
                return 0;
            }

            @Override
            public int colspacing(MyGridView myGridView) {
                return 0;
            }

            @Override
            public int leftpadding(MyGridView myGridView) {
                return 0;
            }

            @Override
            public int toppadding(MyGridView myGridView) {
                return 0;
            }

            @Override
            public int colCount(MyGridView myGridView) {
                return 4;
            }

            @Override
            public int rowHeight(MyGridView myGridView) {
                return mContainer_gridview.getHeight() / 4;
            }

            @Override
            public int viewWidth(MyGridView myGridView) {
                return mContainer_gridview.getWidth();
            }

            @Override
            public int count(MyGridView myGridView) {
                return funcItems.size();
            }

            @Override
            public View cell(int i, MyGridView myGridView) {
                View view = context.getLayoutInflater().inflate(R.layout.server_item_func, null);

                ImageView iv_pic = (ImageView) view.findViewById(R.id.iv_server_fucpic);
                TextView tv_name = (TextView) view.findViewById(R.id.tv_server_fucname);
                FuncItem fi = funcItems.get(i);

                iv_pic.setImageResource(fi.resId);
                tv_name.setText(fi.name);

                return view;
            }

            @Override
            public View title(int i, MyGridView myGridView) {
                return null;
            }

            @Override
            public int titleOffsetY(MyGridView myGridView) {
                return 0;
            }

            @Override
            public boolean needGridLine(MyGridView myGridView) {
                return false;
            }
        });

        gridView.setListener(new MyGridView.MyGridViewListener() {
            @Override
            public void onCellTouchDown(int i) {

            }

            @Override
            public void onCellTouchUp(int i) {

            }

            @Override
            public void onCellLongPress(int i) {

            }

            @Override
            public void onCellClick(int i) {
                switch (i) {
                    //报警
                    case 0: {
                        Intent t = new Intent(context, AlarmListNoSpinnerActivity.class);
                        t.putExtra("id", std.id);
                        startActivity(t);
                    }
                    break;
                    //内存
                    case 1: {
                        Intent t = new Intent(context, ServerMemoryActivity.class);
                        t.putExtra("ip", std.ip);
                        startActivity(t);
                    }
                    break;
                    //cpu
                    case 2: {
                        Intent t = new Intent(context, ServerCpuActivity.class);
                        t.putExtra("data", std);
                        startActivity(t);
                    }
                    break;
                    //存储信息
                    case 3: {
                        Intent t = new Intent(context, ServerMemoryMessageActivity.class);
                        t.putExtra("ip", std.ip);
                        startActivity(t);
                    }
                    break;
                    //硬件信息
                    case 4: {
                        normalToasty("暂未开放功能");
                    }
                    break;
                    //历史性能
                    case 5: {
                        Intent t = new Intent(context, ServerHistoryActivity.class);
                        t.putExtra("id", std.id);
                        t.putExtra("ip", std.ip);
                        startActivity(t);
                    }
                    break;
                    //配置
                    case 6: {
                        Intent t = new Intent(context, ServerConfigActivity.class);
                        t.putExtra("id", std.id);
                        startActivity(t);
                    }
                    break;
                    //状态
                    case 7: {
                        normalToasty("暂未开放功能");
                    }
                    break;
                    //服务
                    case 8: {
                        normalToasty("暂未开放功能");
                    }
                    break;
                    //基线扫描
                    case 9: {
                        normalToasty("暂未开放功能");
                    }
                    break;
                    //安全漏洞
                    case 10: {
                        normalToasty("暂未开放功能");
                    }
                    break;
                    //启停
                    case 11: {
                        normalToasty("暂未开放功能");
                    }
                    break;
                    //数据库
                    case 12: {
                        openIntent(DBListActivity.class, true);
                    }
                    break;
                    //中间件
                    case 13: {
                        normalToasty("暂未开放功能");
                    }
                    break;
                    //关联
                    case 14: {
                        normalToasty("暂未开放功能");
                    }
                    break;
                }
            }
        });
        LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        mContainer_gridview.addView(gridView.getView(), p);
    }
    /**
     * 点击事件
     */
    @OnClick({R.id.tool_bar_back, R.id.tool_bar_right_text})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tool_bar_back:
                finish();
                break;
            case R.id.tool_bar_right_text:
                normalToasty("暂未开放功能");
                break;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        handler.removeCallbacks(runnable);
    }

    @Override
    protected void onStop() {
        super.onStop();
        handler.removeCallbacks(runnable);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        handler.postDelayed(runnable, 2000);
    }

    @Override
    protected void onResume() {
        super.onResume();
        handler.postDelayed(runnable, 2000);
    }
}
